<template>
  <view class="search-page">
    <!-- 搜索栏 -->
    <view class="search-header">
      <view class="search-input-wrapper">
        <text class="search-icon">🔍</text>
        <input 
          class="search-input" 
          v-model="keyword" 
          placeholder="搜索樱桃商品" 
          confirm-type="search"
          focus
          @confirm="searchProducts"
        />
        <text class="clear-icon" v-if="keyword" @click="clearKeyword">×</text>
      </view>
      <text class="cancel-btn" @click="navigateBack">取消</text>
    </view>
    
    <!-- 历史搜索 -->
    <view class="search-history" v-if="!keyword && searchHistory.length > 0 && !searchResults.length">
      <view class="section-header">
        <text class="title">历史搜索</text>
        <text class="clear-btn" @click="clearHistory">清空</text>
      </view>
      <view class="history-list">
        <view 
          class="history-item" 
          v-for="(item, index) in searchHistory" 
          :key="index"
          @click="useHistoryKeyword(item)"
        >
          {{ item }}
        </view>
      </view>
    </view>
    
    <!-- 热门搜索 -->
    <view class="hot-search" v-if="!keyword && !searchResults.length">
      <view class="section-header">
        <text class="title">热门搜索</text>
      </view>
      <view class="hot-list">
        <view 
          class="hot-item" 
          v-for="(tag, index) in hotTags" 
          :key="index"
          :class="{ hot: index < 3 }"
          @click="useHistoryKeyword(tag)"
        >
          {{ tag }}
          <view class="hot-icon" v-if="index < 3">{{ index + 1 }}</view>
        </view>
      </view>
    </view>
    
    <!-- 搜索结果 -->
    <view class="search-result" v-if="hasSearched">
      <view class="result-header">
        <view 
          class="tab" 
          :class="{ active: sortBy === 'default' }" 
          @click="changeSort('default')"
        >
          综合
        </view>
        <view 
          class="tab" 
          :class="{ active: sortBy === 'sales' }" 
          @click="changeSort('sales')"
        >
          销量
        </view>
        <view 
          class="tab" 
          :class="{ active: sortBy.startsWith('price') }" 
          @click="changeSort('price')"
        >
          价格
          <text class="icon" :class="{ up: sortBy === 'price_asc' }">▼</text>
        </view>
      </view>
      
      <view class="result-list" v-if="searchResults.length > 0">
        <view 
          class="result-item" 
          v-for="(product, index) in searchResults" 
          :key="product.id"
          @click="goToDetail(product.id)"
        >
          <image class="item-image" :src="product.image" mode="aspectFill"></image>
          <view class="item-info">
            <view class="item-name">{{ product.name }}</view>
            <view class="item-desc">{{ product.subtitle }}</view>
            <view class="price-info">
              <view class="price">{{ product.price.toFixed(2) }}</view>
              <view class="original-price" v-if="product.originalPrice">{{ product.originalPrice.toFixed(2) }}</view>
            </view>
            <view class="sold-info">
              <view class="sold-count">已售{{ product.sales }}件</view>
              <view class="add-cart-btn" @click.stop="addToCart(product)">+</view>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 无搜索结果 -->
      <view class="empty-result" v-else>
        <image class="empty-image" src="/static/images/empty-search.png"></image>
        <view class="empty-text">抱歉，没有找到相关商品</view>
      </view>
      
      <!-- 加载更多 -->
      <view class="loading-more" v-if="loading">
        加载中...
      </view>
      
      <!-- 没有更多数据 -->
      <view class="no-more" v-if="searchResults.length > 0 && !hasMore">
        没有更多了
      </view>
    </view>
  </view>
</template>

<script>
import { mapActions } from 'vuex';
import productApi from '@/api/product.js';
import '@/styles/pages/product/search.scss';

export default {
  data() {
    return {
      keyword: '',
      searchResults: [],
      searchHistory: [],
      hasSearched: false,
      loading: false,
      hasMore: true,
      page: 1,
      limit: 10,
      sortBy: 'default',
      hotTags: []
    };
  },
  onLoad(options) {
    // 如果有传入关键词，直接搜索
    if (options.keyword) {
      this.keyword = options.keyword;
      this.searchProducts();
    }
    
    // 获取历史搜索记录
    this.getSearchHistory();
    
    // 获取热门搜索
    this.getHotSearchKeywords();
  },
  onReachBottom() {
    if (this.hasMore && !this.loading && this.hasSearched) {
      this.loadMore();
    }
  },
  methods: {
    ...mapActions({
      addToCartAction: 'cart/addToCart'
    }),
    
    // 获取热门搜索
    async getHotSearchKeywords() {
      try {
        const res = await productApi.getHotSearchKeywords();
        this.hotTags = res || [];
      } catch (error) {
        console.error('获取热门搜索失败', error);
        // 设置默认热门搜索词
        this.hotTags = ['有机樱桃', '樱桃礼盒', '车厘子', '新鲜水果', '樱桃酒'];
      }
    },
    
    // 获取历史搜索
    async getSearchHistory() {
      try {
        const res = await productApi.getSearchHistory();
        this.searchHistory = res || [];
      } catch (error) {
        console.error('获取搜索历史失败', error);
        // 从本地存储获取
        const history = uni.getStorageSync('searchHistory');
        if (history) {
          this.searchHistory = JSON.parse(history);
        }
      }
    },
    
    // 清空历史记录
    async clearHistory() {
      try {
        await productApi.clearSearchHistory();
        this.searchHistory = [];
        
        // 同时清除本地存储
        uni.removeStorageSync('searchHistory');
        
        uni.showToast({
          title: '已清空历史',
          icon: 'success'
        });
      } catch (error) {
        console.error('清空历史失败', error);
      }
    },
    
    // 添加到历史记录
    async addToHistory(keyword) {
      try {
        await productApi.saveSearchKeyword(keyword);
        
        // 更新本地历史记录
        // 如果已存在，先移除
        const index = this.searchHistory.indexOf(keyword);
        if (index > -1) {
          this.searchHistory.splice(index, 1);
        }
        
        // 添加到开头
        this.searchHistory.unshift(keyword);
        
        // 限制数量
        if (this.searchHistory.length > 10) {
          this.searchHistory = this.searchHistory.slice(0, 10);
        }
        
        // 保存到本地存储
        uni.setStorageSync('searchHistory', JSON.stringify(this.searchHistory));
      } catch (error) {
        console.error('保存搜索关键词失败', error);
      }
    },
    
    // 搜索商品
    async searchProducts() {
      if (!this.keyword.trim()) {
        return;
      }
      
      this.loading = true;
      this.hasSearched = true;
      this.page = 1;
      this.searchResults = [];
      
      // 添加到历史记录
      this.addToHistory(this.keyword);
      
      uni.showLoading({
        title: '搜索中...'
      });
      
      try {
        const params = {
          page: this.page,
          limit: this.limit,
          keyword: this.keyword,
          sort: this.sortBy
        };
        
        const res = await productApi.getProductList(params);
        this.searchResults = res.data || [];
        this.hasMore = res.data.length === this.limit;
        this.page++;
        
        uni.hideLoading();
      } catch (error) {
        console.error('搜索商品失败', error);
        uni.hideLoading();
        uni.showToast({
          title: '搜索失败，请重试',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },
    
    // 加载更多
    async loadMore() {
      if (!this.hasMore || this.loading) return;
      
      this.loading = true;
      
      try {
        const params = {
          page: this.page,
          limit: this.limit,
          keyword: this.keyword,
          sort: this.sortBy
        };
        
        const res = await productApi.getProductList(params);
        const newData = res.data || [];
        
        this.searchResults = [...this.searchResults, ...newData];
        this.hasMore = newData.length === this.limit;
        this.page++;
      } catch (error) {
        console.error('加载更多失败', error);
        uni.showToast({
          title: '加载失败，请重试',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },
    
    // 改变排序方式
    changeSort(sortType) {
      if (sortType === 'price') {
        // 价格排序在升序降序间切换
        if (this.sortBy === 'price_asc') {
          this.sortBy = 'price_desc';
        } else {
          this.sortBy = 'price_asc';
        }
      } else {
        this.sortBy = sortType;
      }
      
      // 重新搜索
      if (this.hasSearched) {
        this.page = 1;
        this.searchResults = [];
        this.searchProducts();
      }
    },
    
    // 清除关键词
    clearKeyword() {
      this.keyword = '';
      this.searchResults = [];
      this.hasSearched = false;
    },
    
    // 使用历史/热门关键词
    useHistoryKeyword(keyword) {
      this.keyword = keyword;
      this.searchProducts();
    },
    
    // 返回上一页
    navigateBack() {
      uni.navigateBack();
    },
    
    // 前往商品详情
    goToDetail(id) {
      uni.navigateTo({
        url: `/pages/product/detail?id=${id}`
      });
    },
    
    // 添加到购物车
    addToCart(product) {
      const cartItem = {
        id: product.id,
        name: product.name,
        image: product.image,
        price: product.price,
        spec: product.specs ? product.specs[0] : '默认',
        quantity: 1,
        selected: true
      };
      
      this.addToCartAction(cartItem);
      
      uni.showToast({
        title: '已加入购物车',
        icon: 'success'
      });
    }
  }
};
</script> 